import * as actionTypes from './constants'
import { PER_PAGE_NUMBER } from './constants'

import {
  getSongCategory,
  getSongCategoryList
} from '@/services/songs'

import { handleSongsCategory } from '@/utils/handle-data'

const changeCategoriesAction = res => ({
  type: actionTypes.CHANGE_CATEGORIES,
  categories: res,
})

const changeCategorySongsAction = res => ({
  type: actionTypes.CHANGE_CATEGORY_SONGS,
  categorySongs: res,
})

export const changeCurrentCategoryAction = name => ({
  type: actionTypes.CHANGE_CURRENT_CATEGORY,
  currentCategory: name,
})

export const getSongCategoryAction = () => {
  return dispatch => {
    getSongCategory().then(res => {
      const categoryData = handleSongsCategory(res);
      dispatch(changeCategoriesAction(categoryData));
    })
  }
}

export const getSongCategoryListAction = (page) => {
  return (dispatch, getState) => {
    // 1. 获取 currentCategory
    const name = getState().getIn(["songs", "currentCategory"]);

    // 2. 获取数据
    getSongCategoryList(name, page * PER_PAGE_NUMBER).then(res => {
      dispatch(changeCategorySongsAction(res));
    })
  }
}